package com.rzico.sbl.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.amap.api.AMapLocationHelper
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.lzg.OkGoHelper
import com.lzy.okgo.utils.OkLogger
import com.rzico.sbl.BuildConfig
import com.rzico.sbl.R
import com.rzico.sbl.model.Const
import com.rzico.sbl.other.driverEnable
import com.rzico.sbl.other.serviceId
import com.rzico.sbl.other.userRole
import com.rzico.sbl.service.DaemonJobService
import com.rzico.sbl.service.ForegroundService
import com.rzico.sbl.ui.report.other.ReportService
import com.rzico.sbl.viewmodel.MainViewModel
import com.tim.library.login
import com.umeng.analytics.MobclickAgent
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.orEmpty
import com.xinnuo.common.extend.requestForResult
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.helper.ActivityStack
import com.xinnuo.common.helper.AppSettingHelper.checkIgnoreBatteryOptimizations
import com.xinnuo.common.helper.AppSettingHelper.requestBatteryOptimizations
import com.xinnuo.common.helper.MD5
import com.xinnuo.common.helper.checkPermission
import com.xinnuo.common.helper.getBoolean
import com.xinnuo.common.helper.getDeviceId
import com.xinnuo.common.helper.getString
import com.xinnuo.common.helper.getVerCode
import com.xinnuo.common.helper.putShared
import com.xinnuo.common.manager.LocationManager
import com.xinnuo.common.manager.PhoneStateManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.objectbox.getBoxEuery
import com.xinnuo.objectbox.model.AppLoginData
import com.xinnuo.objectbox.model.AppLoginData_
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : BaseActivity(R.layout.activity_main) {

    // 前台服务对象
    private val mForeground by lazy { Intent(this, ForegroundService::class.java) }

    override fun getViewModel() = get<MainViewModel>()

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initData() {
        setToolbarVisibility(isVisible = false)

        setupActionBarWithNavController(
            findNavController(R.id.nav_host_fragment)
                .apply {
                    find<BottomNavigationView>(R.id.nav_view)
                        .also {
                            val roleId = userRole
                            val service = serviceId

                            when (roleId) {
                                // 管理员1、店长2
                                "1", "2" -> {
                                    driverEnable.conditionElse(
                                        actionTrue = {
                                            setGraph(R.navigation.main_navigation_driver)
                                            it.inflateMenu(R.menu.bottom_nav_main_driver)
                                        },
                                        actionFalse = {
                                            setGraph(R.navigation.main_navigation)
                                            it.inflateMenu(R.menu.bottom_nav_main)
                                        }
                                    )
                                }
                                // 总经理6、业务经理7
                                "6", "7" -> {
                                    setGraph(R.navigation.main_navigation_manager)
                                    it.inflateMenu(R.menu.bottom_nav_main_manager)
                                }
                                // 总库管8、副库管9
                                "8", "9" -> {
                                    setGraph(R.navigation.main_navigation_depot)
                                    it.inflateMenu(R.menu.bottom_nav_main_depot)
                                }
                                // 财务5
                                "5" -> {
                                    when (service) {
                                        // 财务接单模式
                                        in ReportService.MODE_FINANCE -> {
                                            setGraph(R.navigation.main_navigation_qf)
                                            it.inflateMenu(R.menu.bottom_nav_main_qf)
                                        }
                                        // 司机接单模式
                                        else -> {
                                            setGraph(R.navigation.main_navigation_role)
                                            it.inflateMenu(R.menu.bottom_nav_main_role)
                                        }
                                    }
                                }
                                // 办公室11
                                "11" -> {
                                    when (service) {
                                        // 财务接单模式
                                        in ReportService.MODE_FINANCE -> {
                                            setGraph(R.navigation.main_navigation_qf)
                                            it.inflateMenu(R.menu.bottom_nav_main_qf)
                                        }
                                        // 办公室接单模式
                                        in ReportService.MODE_OFFICE -> {
                                            setGraph(R.navigation.main_navigation_qf)
                                            it.inflateMenu(R.menu.bottom_nav_main_qf)
                                        }
                                        // 司机接单模式
                                        else -> {
                                            setGraph(R.navigation.main_navigation_role)
                                            it.inflateMenu(R.menu.bottom_nav_main_role)
                                        }
                                    }
                                }
                                // 送水工3、推广员4、客服10、自提管理员13、自提店主14、其他
                                else -> {
                                    setGraph(R.navigation.main_navigation_role)
                                    it.inflateMenu(R.menu.bottom_nav_main_role)
                                }
                            }

                            it.itemIconTintList = null
                            it.setupWithNavController(this)
                        }
                },
            AppBarConfiguration(
                setOf(
                    R.id.navigation_home,
                    R.id.navigation_manager,
                    R.id.navigation_statistic,
                    R.id.navigation_mine,
                    R.id.navigation_report_manager,
                    R.id.navigation_report_depot,
                )
            )
        )

        // 开启常驻通知栏，提高应用存活率
        when {
            // 8.0以上的开启方式不同
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> startForegroundService(mForeground)
            else -> startService(mForeground)
        }

        // 友盟启用账号统计
        MobclickAgent
            .onProfileSignIn("${getString("phone")}_${getString("uid")}")

        // 腾讯云
        loginTim()

        // 电池白名单
        checkIgnoreBatteryOptimizations(
            onGranted = {
                getViewModel().showBatteryDialog(baseContext)

                checkUpdate()
            },
            onDenied = {
                requestForResult {
                    getViewModel().showBatteryDialog(baseContext)

                    checkUpdate()
                }.requestBatteryOptimizations(baseContext)
            }
        )

        // 账户同步拉活，华为上架不允许
        ("huawei" !in BuildConfig.FLAVOR
                && "third" !in BuildConfig.FLAVOR)
            .condition {
                getString(R.string.app_name)
                    .apply {
                        try {
                            // 反射解析类
                            Class.forName("com.xinnuo.account.AccountHelper")?.run {
                                // 获取私有构造
                                val con = getDeclaredConstructor()
                                con.isAccessible = true

                                // 获取公有反射方法
                                getDeclaredMethod(
                                    "addAccount",
                                    Context::class.java,
                                    String::class.java
                                ).also {
                                    it.invoke(con.newInstance(), getIContext(), this@apply)
                                }

                                // 获取公有反射方法
                                getDeclaredMethod(
                                    "autoSyncStart",
                                    Context::class.java,
                                    String::class.java
                                ).also {
                                    it.invoke(con.newInstance(), getIContext(), this@apply)
                                }
                            }
                        } catch (e: ClassNotFoundException) {
                            e.printStackTrace()
                        }
                    }
            }

        // JobScheduler 拉活
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            DaemonJobService.startJob(this)

        // 定位方式判断
        (getVerCode().toInt() < 100)
            .conditionElse(
                actionTrue = {
                    // 高德定位初始化
                    getViewModel().initLocation(baseContext)
                    if (getBoolean("isLocation")
                        && checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                    ) {
                        AMapLocationHelper
                            .getInstance(baseContext)
                            .startLocation()
                    }
                },
                actionFalse = {
                    // GPS定位监听
                    getViewModel().initGpsListener()
                    if (getBoolean("isLocation")
                        && checkPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                    ) {
                        LocationManager
                            .instance
                            .enableLocation()
                    }

                }
            )

        // 设置公共请求头
        checkCommonHeader()

        // 设置来电监听
        PhoneStateManager
            .instance
            .registerListener(
                onRinging = { _, phone ->
                    val callTelEnable =
                        getBoxEuery<AppLoginData>()
                            .equal(AppLoginData_.isLogin, true)
                            .build()
                            .findFirst()
                            ?.callTelEnable ?: "1"

                    phone?.let {
                        (userRole in "1,2,10"
                                && callTelEnable == "1"
                                && getString("incomeStatus") == "1")
                            .condition {
                                getViewModel().reportPhone(it)
                            }
                    }
                }
            )
    }

    /**
     * 判断定位权限是否开启
     */
    override fun onStart() {
        super.onStart()

        getBoolean("isLocation")
            .condition {
                checkPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                    .conditionFalse {
                        putShared("isLocation", false)
                        getViewModel().clearLocation()
                    }
            }
    }

    /**
     * 这里重写onSupportNavigationUp()方法，目的时将back时间委托出去
     * 若堆栈中由两个以上Fragment，点击back键就会返回到上一个Fragment
     */
    override fun onSupportNavigateUp() =
        supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment)
            ?.let {
                NavHostFragment.findNavController(it).navigateUp()
            } ?: super.onSupportNavigateUp()

    /**
     * 退出时，将应用切换到后台
     */
    override fun onBackPressed() {
        onSupportNavigateUp()
            .conditionFalse {
                moveTaskToBack(false)
            }
    }

    @SuppressLint("MissingPermission")
    override fun onDestroy() {
        super.onDestroy()
        (getVerCode().toInt() < 642)
            .conditionElse(
                actionTrue = {
                    // 销毁定位
                    AMapLocationHelper
                        .getInstance(baseContext)
                        .destroyLocation()
                },
                actionFalse = {
                    // 关闭GPS定位
                    LocationManager
                        .instance
                        .cancelScope()
                        .disableLocation()
                }
            )

        // 清除常驻通知栏
        stopService(mForeground)

        // 清除来电监听
        PhoneStateManager
            .instance
            .unRegisterListener()
    }

    /**
     * 腾讯云登录
     */
    private fun loginTim() {
        login(
            context = getIContext(),
            userId = getString("userId"),
            userSign = getString("userSign")
        ) {
            onSuccess {
                OkLogger.i("腾讯云即时通讯登录成功！")

                getViewModel().setIMPushOnline()
            }

            onError { errCode, errMsg ->
                OkLogger.e("登录失败：errorCode=$errCode, errorInfo=$errMsg")

                (errCode == 6208).condition { showToast(errMsg.orEmpty()) }

                startActivityEx<LoginActivity>("offLine" to true)
                ActivityStack.screenManager.popActivities(this::class.java)
            }
        }
    }

    /**
     * 检查版本更新
     */
    private fun checkUpdate() {
        lifecycleScope.launch {
            delay(500)

            getViewModel()
                .checkUpdate(
                    context = baseContext,
                    slience = true
                )
        }
    }

    /**
     * OkGo公共请求头配置，防止应用后台长时间丢失
     */
    private fun checkCommonHeader() {
        OkGoHelper
            .commonHeaders {
                val uid = getDeviceId()
                val time = System.currentTimeMillis().toString()

                put("x-uid", uid)
                put("x-app", packageName)
                put("x-tsp", time)
                put("x-tkn", MD5.md5(uid + packageName + time + Const.APP_HEADER_KEY))
                put("x-mid", getString("uid"))
            }
    }

}